package cn.edu.sasu;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.edu.sasu.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.MessageQueue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import cn.edu.sasu.adapter.newsdetail.newsitem.NewsItemAdapter;
import cn.edu.sasu.domain.News;
import cn.edu.sasu.http.HttpNewsService;
import cn.edu.sasu.http.HttpUrl;
import cn.edu.sasu.utils.ActivityUtil;
import cn.edu.sasu.view.NewsListView;
import cn.edu.sasu.view.NewsListView.OnRefreshListener;

@SuppressLint("HandlerLeak")
public class NewsCooperateCommunionActivity extends Activity {

	private NewsListView listView;

	private Map<String, String> params;
	private HttpNewsService newsService;
	private String title;
	private NewsItemAdapter adapter;
	private List<News> list;

	private ViewSwitcher viewSwitcher;

	private Button loadMoreButton;

	private ActivityUtil activityUtil;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news_cooperatecommunion);
		setTheme(android.R.style.Theme_Translucent_NoTitleBar);

		initViews();
		requestRSSFeed();

	}

	private void initViews() {
		viewSwitcher = (ViewSwitcher) findViewById(R.id.viewswitcher_news_finance);
		listView = new NewsListView(this);
		listView.setCacheColorHint(Color.argb(0, 0, 0, 0));

		loadMoreButton = new Button(this);
		loadMoreButton.setBackgroundResource(R.drawable.refresh1);
		loadMoreButton.setHint(21 + "");

		activityUtil = new ActivityUtil();
		loadMoreButton.setOnClickListener(onClickListener);
		listView.addFooterView(loadMoreButton);
		listView.setonRefreshListener(new OnRefreshListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onRefresh() {
				new AsyncTask<Map<String, String>, Integer, List<News>>() {

					@Override
					protected List<News> doInBackground(
							Map<String, String>... params) {
						try {
							Thread.sleep(1000);
						} catch (Exception e) {
							e.printStackTrace();
						}
						data();
						return list;
					}

					@Override
					protected void onPostExecute(List<News> result) {
						loadMoreButton.setHint(21 + "");
						listView.setAdapter(new NewsItemAdapter(list,
								NewsCooperateCommunionActivity.this));
						listView.onRefreshComplete();
					}

				}.execute();
			}
		});
		viewSwitcher.addView(listView);
		viewSwitcher.addView(getLayoutInflater().inflate(
				R.layout.progress_page, null));
		viewSwitcher.showNext();
		listView.setOnItemClickListener(listener);
		newsService = new HttpNewsService();
		params = new HashMap<String, String>();
		title = this.getIntent().getStringExtra("title");

	}

	private int startIndex = 0;
	private int endIndex = 0;
	private OnClickListener onClickListener = new View.OnClickListener() {
		@SuppressWarnings("static-access")
		@Override
		public void onClick(View v) {

			// 设置正在刷新的图片
			loadMoreButton.setBackgroundResource(R.drawable.refresh2);

			final AnimationDrawable rocketAnimation = (AnimationDrawable) loadMoreButton
					.getBackground();

			// 在Android4.0以前，这个方法是要放在操作主线程的UI中去做的，因为开始的时候，可能背景还没有绑定完成
			getMainLooper().myQueue().addIdleHandler(
					new MessageQueue.IdleHandler() {
						@Override
						public boolean queueIdle() {
							rocketAnimation.start();
							return false;
						}
					});

			startIndex = Integer.parseInt(loadMoreButton.getHint().toString());
			endIndex = startIndex + ActivityUtil.COUNT;

			new Thread() {
				@Override
				public void run() {
					list = activityUtil.nextPage(list, startIndex, endIndex,
							HttpUrl.URL_NEWS_COOPERATECOMMUNION);
					handler.sendEmptyMessage(3);
				}
			}.start();

		}
	};

	private void requestRSSFeed() {
		Thread t = new Thread() {
			@Override
			public void run() {
				super.run();
				try {
					data();
					if (list.size() == 0) {
						handler.sendEmptyMessage(-1);
					} else {
						handler.sendEmptyMessage(1);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		t.start();
	}

	private void data() {
		params.clear();
		params.put("news.newsTitle", title);
		String data = newsService.requestByPost(
				HttpUrl.url(HttpUrl.NEWS_SELECT), params);
		list = newsService.parseNews(data);

	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 1) {
				adapter = new NewsItemAdapter(list,
						NewsCooperateCommunionActivity.this);
				listView.setOnItemClickListener(listener);
				listView.setAdapter(adapter);
				viewSwitcher.showPrevious();
			} else if (msg.what == 3) {
				if (list == null) {
					Toast.makeText(NewsCooperateCommunionActivity.this,
							R.string.no_more_news, Toast.LENGTH_SHORT).show();
				} else {
					adapter.notifyDataSetChanged();
					loadMoreButton.setHint(endIndex + "");
					loadMoreButton.setText(getString(R.string.gong)
							+ list.size() + getString(R.string.tiao));
				}
				loadMoreButton.setBackgroundResource(R.drawable.refresh1);
			}

		};
	};

	private OnItemClickListener listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Intent intent = new Intent(NewsCooperateCommunionActivity.this,
					NewsContentActivity.class);
			intent.putExtra("content_url", list.get(position - 1).getNewsId()
					+ "");
			intent.putExtra("count", list.get(position - 1).getCommentsCount()
					+ "");
			NewsCooperateCommunionActivity.this.startActivityForResult(intent,
					position);
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		System.out.println(getString(R.string.back));
		if (resultCode == RESULT_OK) {
			// 确认中
			View v = (View) listView.getItemAtPosition(requestCode);
			TextView tv = (TextView) v
					.findViewById(R.id.tv_title_news_top_item);
			tv.setText("hello");
			adapter.notifyDataSetChanged();
		}
	}
}